/**
 * Qilin-web项目统一请求封装处理
 * @author Qilin
 * @description 全局项目关于动态iconfont图标库的统一获取处理
 * @createDate 2025-01-20
 * @lastUpdateDate 2025-03-26
 */

import axios from "axios";
import Qilin from "qilin-utils";
import {baseUrl} from "@/setting.js";
import {loading} from "@/global/utils/loading.js";

const service = axios.create({
    baseURL:baseUrl,
    timeout:30 * 1000
});

// 请求拦截器
service.interceptors.request.use((config)=>{
    loading.show();
    const token = Qilin.Storage.getValueSessionStorage("token");
    if(token) config.headers.Authorization = "Bearer " + token;
    return config;
},(error)=>{
    return Promise.reject(error);
});
// 响应拦截器
service.interceptors.response.use((response)=>{
    loading.hide();
    if(response.config.isStream) return response;
    return response.data;
},(error)=>{
    loading.hide();
    if(error?.response?.status === 401){ //token失效
        ElMessage.error({
            message:"token已失效，请重新登录",
            center:true,
            type:"warning"
        });
        Qilin.Storage.removeKeySessionStorage("token");
        location.href="/login";
    }else{
        if(!!error?.response?.data.message){
            ElMessage.error({ //错误提醒
                message:error.response.data.message,
                center:true
            });
        }else{
            ElMessage.error({
                message:"系统错误",
                center:true
            });
        };
    }
    return Promise.reject(error);
});

export default service;
